<template>
    <div class="application-list-container container-min-height home-list-container home-list-container-open">
      <!-- banner -->
       <AgentBanner></AgentBanner>
      <!--- 搜索栏start -->
      <div class="mb-24">
        <TopTabs @tab-click="handelTabClick" :tagsList="perTypeList">
          <div class="flex-between">
            <JustMine  class="mr-12" @change="handelJusetMine"/>
            <el-input
              v-model="searchForm.name"
              @input="handleDebounceSearch"
              placeholder="按名称搜索"
              prefix-icon="Search"
              class="w-240 search-input"
              style="min-width: 320px;"
              clearable
            />
          </div>
        </TopTabs>
      </div>
      <!-- 列表start --->
      <InfiniteScroll
        :size="applicationList.length"
        :total="paginationConfig.total"
        :page_size="paginationConfig.page_size"
        v-model:current_page="paginationConfig.current_page"
        @load="getList"
        :loading="pageLoading"
      >
        <div
            v-loading="paginationConfig.current_page === 1 && pageLoading"
            element-loading-text="正在加载..."
            style="width: 100%;"
            class="loading-page"
            v-if="pageLoading && !applicationList.length"
        ></div>
        <PageEmpty v-if="!applicationList.length && !pageLoading" :type="pageEmptyType" />
        <el-row :gutter="20">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="6"
            v-for="(item, index) in applicationList"
            :key="index"
            class="mb-20"
          >
            <CardBoxAgent
              :title="item.name"
              :description="item.applicationDesc"
              @click="jumpToChat(item)"
              :avatar="item.imgUrl"
              :tyType="item.tyType"
              :createdByName="item.createdByName"
            />
          </el-col>
        </el-row>
      </InfiniteScroll>
    </div>
  </template>
  <script setup lang="ts">
  import { ref, onMounted, reactive } from 'vue'
  import { useRouter } from 'vue-router'
  import useStore from '@/stores'
  import AgentBanner from './components/AgentBanner.vue'
  import { page2 } from '@/servers/ai/api/zhinengti'
  import { debounce } from 'lodash'

  const { application, agent } = useStore()
  const router = useRouter()

  const pageLoading = ref(true)
  const perTypeId = ref()
  const perTypeList = ref()
  const applicationList = ref<any[]>([])
  const pageEmptyType = ref('1')

  const paginationConfig = reactive({
    current_page: 1,
    page_size: 30,
    total: 0
  })

  const searchForm = ref<any>({
    name: '', // 名称
    classification: '', // 分类
    authState: '' // 0-仅自己可见 1-自定义课件范围
  });

  const handelTabClick = (item: any) => {
    searchForm.value.classification =  `${item.value === 'all' ? '' : item.value}`;
    searchHandle();
  };

  const handelJusetMine = (item: boolean) => {
    searchForm.value.authState = item
    searchHandle();
  }

const handleDebounceSearch = debounce(() => {
  searchHandle()
},500)
  function searchHandle() {
    applicationList.value = []
    paginationConfig.current_page = 1
    paginationConfig.total = 0
    getList()
  }

  function jumpToChat(item: any) {
    console.log(item)
    localStorage.setItem('avatar', item.imgUrl || '')
    localStorage.setItem('renderingType', item.renderingType || '')
    router.push('/agent/chat/' + item.maxTyTypeUrl)
    // if (item.tyType === 1) {
    //   router.push('/agent/chat/' + item.maxTyTypeUrl)
    //   return
    // }
    // application.asyncGetAccessToken(item.maxId, loading).then((res: any) => {
    //   // const shareUrl = '/agent/chat?accessToken=' + res?.data?.access_token + '&application_id=' + res?.data?.application_id
    //   const shareUrl = '/agent/chat/' + res?.data?.access_token
    //   router.push(shareUrl)
    // })
  }

  function getList() {
    const params: any = {
      "model": {
        state: true //获取启用状态的
      },
      "size": paginationConfig.page_size,
      "current": paginationConfig.current_page,
    }
    if (searchForm.value.name) {
      params.model.name = searchForm.value.name
      pageEmptyType.value = '2'
    } else {
      pageEmptyType.value = '1'
    }
    if (searchForm.value.classification) params.model.classification = searchForm.value.classification
    if (searchForm.value.authState) params.model.authState = 0
    pageLoading.value = true
    page2(params).then((res: any) => {
      if (res.data.isSuccess) {
        const { records, total } = res.data.data
        applicationList.value.push(...records)
        paginationConfig.total = Number(total)
      }
    }).catch(() => {
      pageEmptyType.value = '3'
    })
    .finally(() => {
      pageLoading.value = false
    })
  }

  onMounted(async() => {
    const options = await agent.getCategorizeOptions()
    perTypeList.value = [ {label: "全部", value: "all"}, ...options]
    perTypeId.value = 'all'
    getList()
  })
  </script>
  <style lang="scss" scoped>
  .application-card-add {
    width: 100%;
    font-size: 14px;
    // min-height: var(--card-min-height);
    border: 1px dashed var(--el-border-color);
    background: var(--el-disabled-bg-color);
    border-radius: 8px;
    box-sizing: border-box;


    &:hover {
      border: 1px solid var(--el-card-bg-color);
      background-color: var(--el-card-bg-color);
    }

    .card-add-button {
      &:hover {
        border-radius: 4px;
        background: var(--app-text-color-light-1);
      }

      :deep(.el-upload) {
        display: block;
        width: 100%;
        color: var(--el-text-color-regular);
      }
    }
  }

  .application-card {
    .status-tag {
      position: absolute;
      right: 16px;
      top: 15px;
    }
  }

  .dropdown-custom-switch {
    padding: 5px 11px;
    font-size: 14px;
    font-weight: 400;

    span {
      margin-right: 26px;
    }
  }

  .box-shadow {
    box-shadow: rgb(222, 222, 222) 10px 10px 10px;
  }

  .mb-20 {
    margin-bottom: 20px;
  }
  .application-list-container {
    .loading-page {
      position: absolute;
      top: 50%;
      margin-top: -19px;
    }
  }
  .home-list-container-open {
    .loading-page {
      margin-top: 74px;
    }
  }


  </style>
